package cn.lmxdev.ptms.handler.exception;

import cn.lmxdev.ptms.bean.vo.ResponseVo;
import cn.lmxdev.ptms.enumeration.impl.BizHttpStateImpl;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.core.annotation.Order;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
@Order(2)
public class ValidationExceptionHandler {
    /* 缺失Servlet请求参数异常处理器 */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public ResponseVo<Object> missingServletRequestParameterException(HttpServletRequest request, HttpServletResponse response, MissingServletRequestParameterException e) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return new ResponseVo<>(BizHttpStateImpl.NO).setMsg("请求参数 " + e.getParameterName() + " 不能为空");
    }

    /* 方法参数无效异常处理器 */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseVo<Object> methodArgumentNotValidException(HttpServletRequest request, HttpServletResponse response, MethodArgumentNotValidException e) {
        StringBuilder errorMessage = new StringBuilder();
        List<ObjectError> objectErrorList = e.getBindingResult().getAllErrors();
        if (!CollectionUtils.isEmpty(objectErrorList))
            for (ObjectError thisObjectError : objectErrorList)
                errorMessage.append(thisObjectError.getDefaultMessage()).append("、");
        else
            errorMessage.append("发生方法参数无效异常、");
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return new ResponseVo<>(BizHttpStateImpl.NO).setMsg(errorMessage.substring(0, errorMessage.length() - 1));
    }
}
